import 'dart:io';

// import 'package:flutter/cupertino.dart';
import 'package:flutter/widgets.dart';
import 'package:path_provider/path_provider.dart';
import 'package:video_thumbnail/video_thumbnail.dart';

VideoThumbUtils get VideoThumb => VideoThumbUtils.instance;

class VideoThumbUtils {
  static VideoThumbUtils get instance {
    return _singleton;
  }

  //保存单例
  static VideoThumbUtils _singleton = VideoThumbUtils._internal();

  //工厂构造函数
  factory VideoThumbUtils() => _singleton;

  //私有构造函数
  VideoThumbUtils._internal();

  // 保存url对应的本地缩略图file
  final _thumbMap = Map<String, File>();

  // url对应本地缩略图的信息
  final _thumbInfoMap = Map<String, VideoThumbInfo>();

  Future<void> setThumb(String url, File file) async {
    if (url.isEmpty) {
      return;
    }

    bool exist = await file.exists();
    if (exist == false) {
      return;
    }

    _thumbMap[url] = file;
  }

  Future<File?> getThumb(
    String url, {
    ImageFormat imageFormat = ImageFormat.JPEG,
    int maxHeight = 0,
    int maxWidth = 0,
    int timeMs = 0,
    int quality = 100,
  }) async {
    File? thumbFile = _thumbMap[url];
    if (thumbFile != null) {
      return thumbFile;
    }

    String path = (await getTemporaryDirectory()).path;
    String thumbnailPath = path + "/publish.jpg";
    final fileName = await VideoThumbnail.thumbnailFile(
      video: url,
      thumbnailPath: thumbnailPath,
      imageFormat: imageFormat,
      quality: quality,
      maxWidth: maxWidth,
      maxHeight: maxHeight,
      timeMs: timeMs,
    );

    File file = File(thumbnailPath);
    setThumb(url, file);
    return file;
  }

  // 获取缩略图的大小
  void getVideoThumbInfo(
    String url, {
    ImageFormat imageFormat = ImageFormat.JPEG,
    int maxHeight = 0,
    int maxWidth = 0,
    int timeMs = 0,
    int quality = 100,
    required Function(VideoThumbInfo?) onVideoThumbInfoListener,
  }) async {
    try {
      VideoThumbInfo? thumbInfo = VideoThumb.getThumbInfo(url);
      if (thumbInfo != null) {
        onVideoThumbInfoListener(thumbInfo);
        return;
      }

      await VideoThumb.getThumb(
        url,
        imageFormat: imageFormat,
        maxWidth: maxWidth,
        maxHeight: maxHeight,
        timeMs: timeMs,
        quality: quality,
      ).then((value) {
        File? thumbFile = value;
        print('-------------------');
        print(thumbFile);
        if (thumbFile != null) {
          VideoThumb.getVideoThumbInfoByFile(
            url: url,
            thumbFile: thumbFile,
            onVideoThumbInfoListener: onVideoThumbInfoListener,
          );
        } else {
          onVideoThumbInfoListener(null);
        }
      }).onError((error, stackTrace) {
        print("getVideoThumbInfo error:${error.toString()}");
        onVideoThumbInfoListener(null);
      }).whenComplete(() {
        print("getVideoThumbInfo whenComplete");
      });
    } catch (e) {
      print("getVideoThumbInfo catch error:${e.toString()}");
      onVideoThumbInfoListener(null);
    }
  }

  /// 根据file获取缩略图信息
  void getVideoThumbInfoByFile({
    required String url,
    required File thumbFile,
    required Function(VideoThumbInfo?) onVideoThumbInfoListener,
  }) async {
    try {
      VideoThumbInfo? thumbInfo = VideoThumb.getThumbInfo(url);
      if (thumbInfo != null) {
        onVideoThumbInfoListener(thumbInfo);
        return;
      }

      Image image = Image.file(thumbFile!);
      image.image.resolve(const ImageConfiguration()).addListener(
            ImageStreamListener(
              (ImageInfo imageInfo, bool synchronousCall) {
                int imageWidth = imageInfo.image.width;
                int imageHeight = imageInfo.image.height;
                VideoThumbInfo videoThumbInfo = VideoThumbInfo(url: url);
                videoThumbInfo.thumbFile = thumbFile;
                videoThumbInfo.width = imageWidth;
                videoThumbInfo.height = imageHeight;
                VideoThumb.setThumbInfo(url, videoThumbInfo);
                onVideoThumbInfoListener(videoThumbInfo);
              },
              onError: (exception, stackTrace) {
                print(
                    "getVideoThumbInfoByFile imageStreamListener onError exception:${exception.toString()},stackTrace:${stackTrace}");
                onVideoThumbInfoListener(null);
              },
            ),
          );
    } catch (e) {
      print("getVideoThumbInfoByFile catch error:${e.toString()}");
      onVideoThumbInfoListener(null);
    }
  }

  void removeThumb(String url) {
    if (url.isEmpty) {
      return;
    }

    _thumbMap.remove(url);
  }

  /// 获取存储缩略图信息
  VideoThumbInfo? getThumbInfo(String url) {
    if (url.isEmpty) {
      return null;
    }

    VideoThumbInfo? thumbInfo = _thumbInfoMap[url];
    return thumbInfo;
  }

  /// 存储缩略图信息
  void setThumbInfo(String url, VideoThumbInfo videoThumbInfo) async {
    if (url.isEmpty) {
      return;
    }

    _thumbInfoMap[url] = videoThumbInfo;
  }

  void removeThumbInfo(String url) {
    if (url.isEmpty) {
      return;
    }

    _thumbInfoMap.remove(url);
  }

  void clear() {
    _thumbMap.clear();
    _thumbInfoMap.clear();
  }
}

class VideoThumbInfo {
  String url; // 原视频地址
  File? thumbFile; // 缩略图本地file
  int? width; // 缩略图的width
  int? height; // 缩略图的height

  VideoThumbInfo({
    required this.url,
  });
}
